import { login } from '@/apis/UserInfo'
import type { UserLoginForm } from '@/models/UserInfo/UserLoginForm'
import { useUserInfoStore } from '@/stores/UserInfo'
import { notification } from 'ant-design-vue'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

export function useLogin(path?: any) {
  const userInfoStore = useUserInfoStore()
  const router = useRouter()

  const loading = ref(false)

  async function onFinish(data: UserLoginForm) {
    if (loading.value) return
    loading.value = true
    try {
      const res = await login(data)
      if (res.data) {
        // 登录成功
        userInfoStore.login(data.userName)
        if (typeof path === 'string') {
          router.replace({ path })
        } else {
          router.replace({ path: '/Home' })
        }
      } else {
        // 登录失败
        notification.error({ message: `登录失败!` })
      }
    } catch (error) {
      notification.error({ message: `登录失败!` })
    }
    loading.value = false
  }

  return { loading, onFinish }
}
